package algotithm.leetcode.listnode.interview0206;

import algotithm.leetcode.listnode.ListNode;

/**
 * @author zhouyanxiang
 * @Date 2021-02-2021/2/21-11:21
 * @URL https://leetcode-cn.com/problems/palindrome-linked-list-lcci/
 * @Title 面试题 02.06. 回文链表
 */
public class Solution {

    public boolean isPalindrome(ListNode head) {
        if (head == null) {
            return true;
        }
        ListNode cur = head;
        ListNode firstTail = test(head);
        ListNode secondHead = firstTail.next;
        ListNode p = reverseList(secondHead);
        boolean res = false;
        while (p != null && !res) {
            if (p.val != cur.val) {
                return false;
            }
            p = p.next;
            cur = cur.next;
        }
        return true;
    }

    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    public ListNode test(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
}
